<!-- 用例详情页面，包括需求用例、模块用例、任务用例 -->
<template>
  <div class="div_box" @click="screenClick">
    <div v-show="showRightMenu" id="right_menu" class="right_menu">
      <el-row>
        <el-col><el-link type="success" @click="setSuccessRight()">执行通过</el-link></el-col>
        <el-col><el-link type="danger" @click="setFailRight()">执行失败</el-link></el-col>
        <el-col><el-link type="warning" @click="setBlockRight()">执行阻塞</el-link></el-col>
      </el-row>
    </div>
    <div style="min-width: 1600px;">
      <!-- 页面布局：头部 -->
      <el-row>
        <el-form ref="form" :inline="true" label-width="80px">
          <el-button size="mini" icon="el-icon-refresh" title="刷新列表" circle @click="getCaseTree" />
          <el-button v-if="demandCasePage" size="mini" icon="el-icon-s-claim" title="创建任务" circle @click="createTask" />
          <el-button v-if="taskCasePage" size="mini" icon="el-icon-s-custom" title="只看自己的用例" circle @click="getCaseTreeMine" />
          <el-button v-if="taskCasePage && !setCaseExectorOpen" size="mini" icon="el-icon-s-promotion" title="指派用例给其他人" circle @click="setCaseExector" />
          <el-button v-if="taskCasePage && setCaseExectorOpen" size="mini" icon="el-icon-circle-close" title="取消" circle @click="setCaseExectorCancle" />
          <el-form-item v-if="taskCasePage && setCaseExectorOpen" label="">
            <el-select v-model="selectUser" collapse-tags filterable style="margin-left: 20px;" placeholder="选择指派人" @change="setCaseExectorConfirm">
              <el-option v-for="item in userList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="demandCasePage || taskCasePage" label="">
            <el-select v-model="selectCheckList" multiple collapse-tags style="margin-left: 20px;" placeholder="结果筛选">
              <el-option v-for="item in selectCheckListOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="demandCasePage || taskCasePage" label="">
            <el-select v-model="selectMouldeList" multiple collapse-tags filterable style="margin-left: 20px;" placeholder="模块筛选">
              <el-option v-for="item in selectModuleListOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="demandCasePage || taskCasePage" label="">
            <el-select v-model="selectLevelList" multiple collapse-tags filterable style="margin-left: 20px;" placeholder="级别筛选">
              <el-option v-for="item in selectLevelListOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="快捷管理">
            <el-button-group>
              <el-button v-if="(demandCasePage || taskCasePage) && !showAddCase" type="primary" size="small" icon="el-icon-circle-plus" title="用例库中选择用例，直接添加" @click="addCaseMethod" />
              <el-button v-if="showAddCase" type="primary" size="small" icon="el-icon-check" title="确定" @click="addCaseDo" />
              <el-button v-if="demandCasePage || taskCasePage" type="primary" size="small" icon="el-icon-s-order" title="上传用例编号文件" />
              <el-button v-if="demandCasePage" type="primary" size="small" icon="el-icon-upload" title="上传用例文件" @click="caseUpload" />
              <el-button v-if="demandCasePage || taskCasePage" type="primary" size="small" icon="el-icon-remove" title="移除用例" @click="removeCaseDo" />
              <el-button v-if="demandCasePage" type="primary" size="small" icon="el-icon-delete-solid" title="删除用例" @click="trueDelete" />
              <el-button v-if="allFolderClose" type="primary" size="small" icon="el-icon-folder-opened" title="全部展开" @click="clickOpenAllFolder" />
              <el-button v-if="!allFolderClose" type="primary" size="small" icon="el-icon-folder" title="全部折叠" @click="clickCloseAllFolder" />
              <el-button v-if="taskCasePage" type="primary" size="small" icon="el-icon-s-order" title="查看报告" @click="taskReport" />
            </el-button-group>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 可拖拽宽高组件 -->
      <div class="components-container">
        <split-pane class="case-spilt-div" :min-percent="10" :default-percent="90" split="horizontal" @resize="resize">
          <!-- 页面布局：中部 -->
          <template slot="paneL">
            <split-pane :min-percent="15" :default-percent="15" split="vertical">
              <!-- 页面布局：中部·左 -->
              <!-- 用例树 -->
              <template slot="paneL">
                <div class="left-container">
                  <el-tree
                    ref="caseTreeRef"
                    :data="caseTreeData"
                    :props="defaultProps"
                    node-key="id"
                    :default-expanded-keys="defaultExpandedKeys"
                    :default-expand-all="defaultExpandAll"
                    :filter-node-method="filterNode"
                    :highlight-current="true"
                    show-checkbox
                    :draggable="draggable && demandCasePage"
                    :allow-drop="allowDrop"
                    :allow-drag="allowDrag"
                    @node-click="handleCaseNodeClick"
                    @node-drag-start="handleDragStart"
                    @node-drag-end="handleDragEnd"
                    @node-expand="handleCaseNodeExpend"
                    @node-collapse="handleCaseNodeCollapse"
                    @node-contextmenu="rightClick"
                  >
                    <span slot-scope="{ node, data }" class="custom-case-tree" style="width: 100%;">
                      <span :title="data.title" tabindex="0" @keyup.f1="setSuccess(node)" @keyup.f2="setFail(node)" @keyup.f3="setBlock(node)" @keyup.f4="removeLastResult(node)">
                        <svg-icon :icon-class="node.data.icon" />
                        <el-tag v-if="node.data.personInCharge" type="success" size="mini">{{ node.data.personInCharge }}</el-tag>
                        <span :title="node.data.label" style="font-size: 14px;">{{ node.data.label }}</span>
                      </span>
                    </span>
                  </el-tree>
                </div>
              </template>
              <!-- 页面布局：中部·右 -->
              <template slot="paneR">
                <div class="right-container">
                  <!-- 内部宽度固定 -->
                  <div style="width: 1200px;">
                    <!-- 文件夹详情 -->
                    <div v-if="rightView == 1 && demandCasePage" id="case-folder">
                      <el-form ref="creatorForm" :model="creatorForm" label-width="80px">
                        <el-row :gutter="20">
                          <el-col :span="10">
                            <el-form-item label="用例编号">
                              <el-input v-model="creatorForm.caseNum" placeholder="在所有用例中全局唯一，提交时校验。" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="5">
                            <el-form-item label="自动化">
                              <el-radio-group v-model="creatorForm.auto">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                              </el-radio-group>
                            </el-form-item>
                          </el-col>
                          <el-col :span="4">
                            <el-form-item label="级别">
                              <el-select v-model="creatorForm.caseLevel" placeholder="请选择">
                                <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="5">
                            <el-form-item label="关联模块">
                              <el-select v-model="creatorForm.moduleList" multiple filterable allow-create default-first-option placeholder="请选择模块标签">
                                <el-option v-for="item in selectModuleListOption" :key="item.value" :label="item.label" :value="item.value" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="用例名称">
                              <el-input v-model="creatorForm.caseName" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="用例描述">
                              <el-input v-model="creatorForm.caseDesc" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="预置条件" prop="desc">
                              <el-input v-model="creatorForm.beforeTest" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="测试步骤" prop="desc">
                              <el-input v-model="creatorForm.onTest" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="后置操作" prop="desc">
                              <el-input v-model="creatorForm.afterTest" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="预期结果" prop="desc">
                              <el-input v-model="creatorForm.expect" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item>
                              <el-button type="primary" @click="createrOnA()">创建同级目录添加用例</el-button>
                              <el-button type="primary" @click="createrOnB()">创建子目录添加用例</el-button>
                              <el-button type="primary" @click="createrOnC()">仅创建用例</el-button>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-form>
                    </div>
                    <!-- 用例详情 -->
                    <div v-if="rightView == 2" id="case-detail">
                      <el-form ref="caseForm" :model="caseForm" label-width="80px">
                        <el-row :gutter="20">
                          <el-col :span="16">
                            <el-form-item label="用例编号">
                              <el-input v-model="caseForm.caseNum" :disabled="true" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="4">
                            <el-form-item label="级别">
                              <el-select v-model="caseForm.caseLevel" placeholder="请选择">
                                <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="4">
                            <el-form-item label="结果">
                              <el-tag v-if="caseForm.lastResult === 1" type="success">已通过</el-tag>
                              <el-tag v-if="caseForm.lastResult === 0" type="info">未执行</el-tag>
                              <el-tag v-if="caseForm.lastResult === 3" type="warning">阻塞中</el-tag>
                              <el-tag v-if="caseForm.lastResult === 2" type="danger">已失败</el-tag>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="18">
                            <el-form-item label="用例名称">
                              <el-input v-model="caseForm.caseName" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="6">
                            <el-form-item label="自动化">
                              <el-radio-group v-model="caseForm.auto">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                              </el-radio-group>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="用例描述">
                              <el-input v-model="caseForm.caseDetail.caseDesc" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="6">
                            <el-form-item label="创建人">
                              <el-input v-model="caseForm.author" :disabled="true" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="6">
                            <el-form-item label="更新时间">
                              <el-input v-model="caseForm.modifyTime" :disabled="true" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="关联模块">
                              <el-select v-model="caseFormModuleList" multiple filterable allow-create default-first-option placeholder="请选择模块标签">
                                <el-option v-for="item in selectModuleListOption" :key="item.label" :label="item.label" :value="item.label" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <!-- <el-col :span="6">
                            <el-form-item label="相关BUG">
                              <el-input v-model="caseForm.bugs" placeholder="暂未使用" :disabled="true" />
                            </el-form-item>
                          </el-col> -->
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="预置条件" prop="desc">
                              <el-input v-model="caseForm.caseDetail.beforeTest" type="textarea" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="测试步骤" prop="desc">
                              <el-input v-model="caseForm.caseDetail.onTest" type="textarea" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="后置操作" prop="desc">
                              <el-input v-model="caseForm.caseDetail.afterTest" type="textarea" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="24">
                            <el-form-item label="预期结果" prop="desc">
                              <el-input v-model="caseForm.caseDetail.expect" type="textarea" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-form-item>
                            <el-button type="primary" @click="updateModify()">提交修改</el-button>
                            <el-button type="primary" @click="editScript(caseForm.id)">编辑脚本</el-button>
                            <el-button type="primary" @click="todo('caseForm')">执行脚本</el-button>
                            <el-button type="primary" @click="showHistory(caseForm.execInfo)">历史结果</el-button>
                          </el-form-item>
                        </el-row>
                      </el-form>
                    </div>
                  </div>
                </div>
              </template>
            </split-pane>
          </template>
          <!-- 页面布局：底部 -->
          <template slot="paneR">
            <div class="bottom-container">
              todo
            </div>
          </template>
        </split-pane>
      </div>
      <!-- 用例历史，模态框 -->
      <caseHistory ref="caseHistory" />
      <caseUpload ref="caseUpload" @reflushDataList="getCaseTree()" />
    </div>
  </div>
</template>

<script>
import splitPane from 'vue-splitpane'
import { demandCaseTree, taskCaseTree, taskCaseTreeMine, moduleCaseTree, demandAddCaseByIds, demandRemoveCaseByIds, searchDetail, batchSetResult, updateCase, updateTree, createCase, trueDelete, caseTreeTaskParent, taskAddCaseByIds } from '@/api/auto/case.js'
import CaseHistory from './case-list-history'
import CaseUpload from './case-list-upload'
import { findAllModules } from '@/api/auto/module.js'
import { createTask, setCaseExector, taskRemoveCaseByIds } from '@/api/auto/task.js'
import { all } from '@/api/system/user.js'
export default {
  name: 'AutoCaseList',
  components: {
    splitPane,
    CaseHistory,
    CaseUpload
  },
  data() {
    return {
      draggable: true,
      caseTreeData: [{ id: 0, label: '用例列表', icon: 'love-flowers', children: [], root: true }], // 前端页面上的根节点
      caseTreeLoading: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultExpandedKeys: [0], // 默认展开节点
      rightView: 0,
      caseForm: {},
      caseFormModuleList: [],
      creatorForm: { auto: 0, caseLevel: 1 },
      levelOptions: [
        { value: 1, label: 'Level1' },
        { value: 2, label: 'Level2' },
        { value: 3, label: 'Level3' },
        { value: 4, label: 'Level4' },
        { value: 5, label: 'Level5' }
      ],
      selectCheckList: [],
      selectCheckListOption: [
        { value: 'success', label: '成功' },
        { value: 'fail', label: '失败' },
        { value: 'warn', label: '阻塞' },
        { value: 'exception', label: '异常' },
        { value: 'info', label: '空' }
      ],
      selectMouldeList: [],
      selectModuleListOption: [],
      selectLevelList: [],
      selectLevelListOption: [
        { value: '1', label: 'Level 1' },
        { value: '2', label: 'Level 2' },
        { value: '3', label: 'Level 3' },
        { value: '4', label: 'Level 4' },
        { value: '5', label: 'Level 5' }
      ],
      defaultExpandAll: true,
      showAddCase: false,
      allFolderClose: true,
      demandCasePage: false,
      taskCasePage: false,
      resultType: 0,
      resultTypeId: 0,
      showRightMenu: false,
      rightClickNode: null,
      userList: [],
      selectUser: null,
      setCaseExectorOpen: false
    }
  },
  watch: {
    selectCheckList(newValue, oldValue) {
      this.defaultExpandedKeys = []
      this.$refs.caseTreeRef.filter(this.caseTreeData)
    },
    selectMouldeList(newValue, oldValue) {
      console.info(newValue, oldValue)
    }
  },
  created() {
    if (this.$route.params.demandId) {
      this.demandCasePage = true
      this.resultType = 2 // 设置结果是走需求用例结果
      this.resultTypeId = this.$route.params.demandId // 传入参数为需求的ID
    }
    if (this.$route.params.taskId) {
      this.taskCasePage = true
      this.resultType = 3 // 设置结果是走任务用例结果
      this.resultTypeId = this.$route.params.taskId // 传入参数为任务的ID
    }
    this.getCaseTree()
  },
  methods: {
    todo() {
      this.$message('todo')
    },
    test() {
      this.$message('todo')
      console.info(this.$refs.caseTreeRef.getCheckedNodes())
    },
    rightClick(event, data, node, obj) {
      if (data.isCaseNode) {
        this.showRightMenu = true
        this.rightClickNode = node
        const menu = document.getElementById('right_menu')
        menu.style.left = event.clientX - 20 + 'px'
        menu.style.top = event.clientY + 'px'
      }
    },
    // 点击空白处触发
    screenClick() {
      this.showRightMenu = false
    },
    setCaseExector() {
      // 先判断用没有用例选择
      if (this.$refs.caseTreeRef.getCheckedNodes().length === 0) {
        this.$message.warning('请至少选中一个用例！')
        return
      }
      // 然后查询所有的用户名称
      all().then(respnose => {
        if (respnose && respnose.code === 200) {
          this.userList = respnose.data
          this.setCaseExectorOpen = true
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    setCaseExectorCancle() {
      this.setCaseExectorOpen = false
      this.userList = []
      this.selectUser = null
    },
    setCaseExectorConfirm(value) {
      this.$confirm('将选中的用例指派给【' + value + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先获取用例编号数组
        const caseNums = []
        let i = 0
        for (i = 0; i < this.$refs.caseTreeRef.getCheckedNodes().length; i++) {
          if (this.$refs.caseTreeRef.getCheckedNodes()[i].isCaseNode) {
            caseNums.push(this.$refs.caseTreeRef.getCheckedNodes()[i].case_num)
          }
        }
        // 再组装请求对象
        const data = {}
        data.taskId = this.$route.params.taskId
        data.caseNums = caseNums.join(',')
        data.userName = value
        setCaseExector(data).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success(respnose.data)
            this.setCaseExectorCancle()
            this.getCaseTree()
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消指派'
        })
        this.setCaseExectorCancle()
      })
    },
    createrOnA() {
      this.$prompt('请输入目录名称', '用例创建在同级目录下', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.creatorForm.folderType = 1
        this.creatorForm.folderName = value
        this.creatorForm.demandId = this.$route.params.demandId
        this.creatorForm.modules = this.creatorForm.moduleList.join('、')
        console.info(this.creatorForm)
        createCase(this.creatorForm).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('添加成功')
            this.getCaseTree()
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    createrOnB() {
      this.$prompt('请输入目录名称', '用例创建在当前目录的子目录位置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.creatorForm.folderType = 2
        this.creatorForm.folderName = value
        this.creatorForm.demandId = this.$route.params.demandId
        this.creatorForm.modules = this.creatorForm.moduleList.join('、')
        console.info(this.creatorForm)
        createCase(this.creatorForm).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('添加成功')
            this.getCaseTree()
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    createrOnC() {
      this.creatorForm.demandId = this.$route.params.demandId
      this.creatorForm.modules = this.creatorForm.moduleList.join('、')
      console.info(this.creatorForm)
      createCase(this.creatorForm).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success('添加成功')
          this.getCaseTree()
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    createTask() {
      this.$prompt('请输入任务名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        createTask(value, this.$route.params.demandId, this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    addCaseMethod() {
      /**
       * 1. 先把添加按钮隐藏，确认按钮暴露，通过 v-if 实现
       * 2. 然后查询用例库中所有的用例，并可以根据模板筛选
       */
      this.showAddCase = true
      // 如果是需求，查询所有的用例
      if (this.demandCasePage) {
        this.getAllCaseTree()
      }
      // 如果是任务，查询需求中的用例
      if (this.taskCasePage) {
        this.getCaseTreeTaskParent()
      }
    },
    addCaseDo() {
      /**
       * 1. 确认提交选中的用例，添加到当前需求中
       * 2. 添加成功之后隐藏确认按钮，暴露添加按钮
       * 3. 刷新一下用例列表
       */
      if (this.demandCasePage) {
        demandAddCaseByIds(this.$route.params.demandId, this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error(respnose.message)
          }
          this.getCaseTree()
        })
      }
      if (this.taskCasePage) {
        taskAddCaseByIds(this.$route.params.taskId, this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error(respnose.message)
          }
          this.getCaseTree()
        })
      }
    },
    removeCaseDo() {
      if (this.$refs.caseTreeRef.getCheckedKeys().length === 0) {
        this.$message.warning('请至少选择一个用例')
        return
      }
      if (this.demandCasePage) {
        this.$confirm('此操作会将当前用例移除该需求, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          /**
           * 从需求用例表中移除选中的用例
           */
          demandRemoveCaseByIds(this.$route.params.demandId, this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
            if (respnose && respnose.code === 200) {
              this.$message.success('移除成功')
              this.getCaseTree()
            } else {
              this.$message.error(respnose.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
      if (this.taskCasePage) {
        this.$confirm('此操作会将当前用例移除该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          /**
           * 从需求用例表中移除选中的用例
           */
          taskRemoveCaseByIds(this.$route.params.taskId, this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
            if (respnose && respnose.code === 200) {
              this.$message.success('移除成功')
              this.getCaseTree()
            } else {
              this.$message.error(respnose.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    trueDelete() {
      if (this.$refs.caseTreeRef.getCheckedKeys().length === 0) {
        this.$message.warning('请至少选择一个用例')
        return
      }
      this.$confirm('此操作将永久删除选中的用例文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        trueDelete(this.$refs.caseTreeRef.getCheckedKeys().join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success('删除成功')
            this.getCaseTree()
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getCaseModules() {
      /**
       * 查询用例库中所有的模板名称、ID
       */
      findAllModules().then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.selectModuleListOption = data
        } else {
          this.$message.error(respnose.message)
          this.selectModuleListOption = []
        }
      })
    },
    getAllCaseTree() {
      /**
       * 查询所有的用例（不限于当前需求），可以根据模板筛选
       * 用于向需求中添加用例
       * 返回结构是一个 el-tree
       */
      this.caseTreeLoading = true
      moduleCaseTree(this.selectMouldeList.join(',')).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.caseTreeData[0].children = data
        } else {
          this.$message.error(respnose.message)
          this.caseTreeData[0].children = []
        }
        this.caseTreeLoading = false
      })
    },
    getCaseTreeMine() {
      /**
       * 只用于查询任务的用例，查询自己名下的用例
       */
      this.getCaseModules()
      this.caseTreeLoading = true
      this.showAddCase = false
      taskCaseTreeMine(this.$route.params.taskId, this.selectMouldeList.join(','), this.selectLevelList.join(',')).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$refs.caseTreeRef.setCheckedKeys([])
          const { data } = respnose
          this.caseTreeData[0].children = data
        } else {
          this.$message.error(respnose.message)
          this.caseTreeData[0].children = []
        }
        this.caseTreeLoading = false
      })
    },
    getCaseTreeTaskParent() {
      caseTreeTaskParent(this.$route.params.taskId, this.selectMouldeList.join(','), this.selectLevelList.join(',')).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$refs.caseTreeRef.setCheckedKeys([])
          const { data } = respnose
          this.caseTreeData[0].children = data
        } else {
          this.$message.error(respnose.message)
          this.caseTreeData[0].children = []
        }
        this.caseTreeLoading = false
      })
    },
    getCaseTree() {
      /**
       * 查询当前需求的所有用例
       * 返回结构是一个 el-tree
       * 同时查询用例库中的所有模板信息
       */
      this.getCaseModules()
      this.caseTreeLoading = true
      this.showAddCase = false
      if (this.$route.params.demandId) {
        demandCaseTree(this.$route.params.demandId, this.selectMouldeList.join(','), this.selectLevelList.join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$refs.caseTreeRef.setCheckedKeys([])
            const { data } = respnose
            this.caseTreeData[0].children = data
          } else {
            this.$message.error(respnose.message)
            this.caseTreeData[0].children = []
          }
          this.caseTreeLoading = false
        })
      }
      if (this.$route.params.taskId) {
        taskCaseTree(this.$route.params.taskId, this.selectMouldeList.join(','), this.selectLevelList.join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$refs.caseTreeRef.setCheckedKeys([])
            const { data } = respnose
            this.caseTreeData[0].children = data
          } else {
            this.$message.error(respnose.message)
            this.caseTreeData[0].children = []
          }
          this.caseTreeLoading = false
        })
      }
    },
    clickOpenAllFolder() {
      this.allFolderClose = false
      this.changeTreeNodeStatus(this.$refs.caseTreeRef.store.root)
    },
    clickCloseAllFolder() {
      this.allFolderClose = true
      this.changeTreeNodeStatus(this.$refs.caseTreeRef.store.root)
    },
    taskReport() {
      this.$nextTick(() => {
        this.$router.push({
          name: 'AutoCaseTaskReport',
          params: {
            taskId: this.$route.params.taskId
          }
        })
      })
    },
    // 改变节点的状态
    changeTreeNodeStatus(node) {
      node.expanded = !this.allFolderClose
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = !this.allFolderClose
        // 遍历子节点
        if (node.childNodes[i].childNodes.length > 0) {
          this.changeTreeNodeStatus(node.childNodes[i])
        }
      }
    },
    filterNode(value, data, node) {
      /**
       * 过滤用例树，根据结果、名称、用例编号等筛选功能会触发这里
       */
      if (this.selectCheckList.length === 0) {
        return true
      }
      var i = 0
      if (!data.isCaseNode) {
        for (i = 0; i < this.selectCheckList.length; i++) {
          if (JSON.stringify(data.children).indexOf('"icon":' + this.selectCheckList[i]) !== -1) {
            return true
          }
        }
        return false
      }
      for (i = 0; i < this.selectCheckList.length; i++) {
        if (data.icon === this.selectCheckList[i]) {
          this.defaultExpandedKeys.push(data.id)
          node.checked = true
          return true
        }
      }
      node.checked = false
      return false
    },
    handleCaseNodeClick(data) {
      /**
       * 点击用例，查询用例详情
       */
      if (data.isCaseNode) {
        searchDetail(data.id, this.resultType, this.resultTypeId).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.caseForm = data
            this.caseFormModuleList.length = 0
            const modules = this.caseForm.modules.split('、')
            for (var i = 0; i < modules.length; i++) {
              this.caseFormModuleList.push(modules[i])
            }
          } else {
            this.$message.error(respnose.message)
          }
          this.rightView = 2
        })
      } else {
        this.rightView = 1
        this.creatorForm = {}
        this.creatorForm.folderId = -data.id
      }
    },
    handleCaseNodeExpend(data) {
      /**
       * 节点展开，图标切换
       */
      this.defaultExpandedKeys.push(data.id)
      // 根节点是一朵花
      if (data.root) { return }
      data.icon = 'folder-open'
    },
    handleCaseNodeCollapse(data) {
      /**
       * 节点关闭，图标切换
       */
      this.defaultExpandedKeys.splice(this.defaultExpandedKeys.indexOf(data.id), 1)
      // 根节点是一朵花
      if (data.root) { return }
      data.icon = 'folder-close'
    },
    setSuccessRight() {
      this.setSuccess(this.rightClickNode)
    },
    setSuccess(node) {
      /**
       * 设置用例结果为成功
       */
      this.setResult(node, 1, 'NA')
    },
    setFailRight() {
      this.setFail(this.rightClickNode)
    },
    setFail(node) {
      /**
       * 设置用例结果为失败，可以添加原因
       */
      this.$prompt('可以是bugID，也可以是简单的一句话，也可以留空', '请填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.setResult(node, 2, value)
      }).catch(() => {
      })
    },
    setBlockRight() {
      this.setBlock(this.rightClickNode)
    },
    setBlock(node) {
      /**
       * 设置用例结果为阻塞，可以添加原因
       */
      this.$prompt('可以是bugID，也可以是简单的一句话，也可以留空', '请填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.setResult(node, 3, value)
      }).catch(() => {
      })
    },
    setResult(node, result, remark) {
      /**
       * 设置用例结果的基础方法
       */
      const caseIds = []
      caseIds.push(node.data.id)

      if (remark == null) {
        remark = '未设置，请填写原因'
      }
      batchSetResult(caseIds.join(','), result, remark, this.resultType, this.resultTypeId).then(respnose => {
        if (respnose && respnose.code === 200) {
          switch (result) {
            case 1:
              node.data.icon = 'success'
              break
            case 2:
              node.data.icon = 'fail'
              break
            case 3:
              node.data.icon = 'warn'
              break
          }
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    batchSetResult(result) {
      /**
       * 设置用例结果的基础方法，支持批量
       */
      this.$prompt('原因：', '请填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        value = '批量设置结果：' + value
        const caseIds = []
        let i = 0
        for (i = 0; i < this.$refs.caseTreeRef.getCheckedNodes().length; i++) {
          if (this.$refs.caseTreeRef.getCheckedNodes()[i].isCaseNode) {
            caseIds.push(this.$refs.caseTreeRef.getCheckedNodes()[i].id)
          }
        }
        batchSetResult(caseIds.join(','), result, value, this.resultType, this.resultTypeId).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.getCaseTree()
          } else {
            this.$message(respnose.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    showHistory(execInfo) {
      /**
       * 查询用例历史执行结果，显示在一个弹窗里面
       */
      this.$nextTick(() => {
        this.$refs.caseHistory.init(execInfo)
      })
    },
    editScript(id) {
      /**
       * 编辑脚本，跳转到一个新页面处理
       */
      // 这里不要删除缓存了
      // this.$store.dispatch('tagsView/delView', { name: 'AutoCaseScript', path: '/auto/auto-case-script' })
      this.$nextTick(() => {
        this.$router.push({
          name: 'AutoCaseScript',
          params: {
            caseId: id
          }
        })
      })
    },
    updateModify() {
      /**
       * 编辑用例信息，保存
       */
      this.$prompt('说明修改了那些东西，留做记录', '请填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (!value || value === '') {
          this.caseForm.remark = 'NA'
        } else {
          this.caseForm.remark = value
        }
        this.caseForm.modules = this.caseFormModuleList.join('、')
        console.info(this.caseForm)
        updateCase(this.caseForm).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.caseForm = data
            this.caseFormModuleList.length = 0
            const modules = this.caseForm.modules.split('、')
            for (var i = 0; i < modules.length; i++) {
              this.caseFormModuleList.push(modules[i])
            }
            this.$message.success(respnose.message)
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
      })
    },
    caseUpload() {
      /**
       * 上传用例，打开是一个弹窗
       */
      this.$nextTick(() => {
        this.$refs.caseUpload.init(this.$route.params.demandId)
      })
    },
    // 是否允许放下
    allowDrop(draggingNode, dropNode, type) {
      // 最上面的节点不允许拖拽放置
      if (dropNode.data.label === '用例列表') {
        return false
      }
      // return !dropNode.data.isCaseNode
      return true
    },
    // 是否允许托起
    allowDrag(draggingNode) {
      // 最上面的节点不允许拖拽放置
      if (draggingNode.data.label === '用例列表') {
        return false
      }
      return true
    },
    handleDragStart(node, ev) {
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      /**
       * 控制用例结构移动的核心方法
       */
      var caseFolderSortS = []
      var caseDetailSortS = []
      var brotherNodes = dropType === 'inner' ? dropNode.childNodes : dropNode.parent.childNodes

      for (var i = 0; i < brotherNodes.length; i++) {
        brotherNodes[i].data.isCaseNode ? caseDetailSortS.push(brotherNodes[i].data.id) : caseFolderSortS.push(brotherNodes[i].data.id)
      }

      this.caseTreeLoading = true
      updateTree(
        draggingNode.data.id,
        dropNode.data.id,
        draggingNode.data.isCaseNode ? 1 : 0,
        dropNode.data.isCaseNode ? 1 : 0,
        dropType,
        caseFolderSortS.join(','),
        caseDetailSortS.join(',')
      ).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
        } else {
          this.$message.error(respnose.message)
        }
        this.getCaseTree()
      })
    },
    resize() {}
  }
}
</script>

<style scoped="scoped">
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.el-tree>.el-tree-node{
  min-width:100%;
  display: inline-block;
}
.div_box {
  border: 1px solid #eee;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 15px;
  padding-bottom: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
}

.components-container {
  position: relative;
  height: 75vh;
  margin: 0;
}

.left-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}

.right-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}

.top-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}

.bottom-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}

.case-spilt-div {
  background: #FFFFFF;
  border:1px solid #eeeeee;
  margin: 10px 10px 10px 10px;
}

.right_menu {
  position: absolute;
  padding: 5px;
  width: 70px;
  height: 80px;
  background: rgb(248, 248, 249);
  border: 1px solid rgb(241, 241, 241);
  border-radius: 5%;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 30%);
  z-index: 99999;
}
</style>
<style type="text/css">
/* 参考：https://www.tqwba.com/x_d/jishu/174642.html */
/* 不能在scoped中添加，在scoped中写不会生效 */
.el-select__tags {
  flex-wrap: nowrap;
  overflow: hidden;
}
</style>
